package net.zjitc.dao.product.productDaoImpl;

import net.zjitc.dao.product.ProductDao;
import net.zjitc.domain.Product;
import net.zjitc.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;


/**
 * Created by hasee on 2017/10/18.
 */
public class ProductDaoImpl implements ProductDao {
    @Override
    public List<Product> findAll() {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataScource());
        String sql = "select * from product";
        List<Product> list = null;
        try {
            list = (List) runner.query(sql,new BeanListHandler(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Product findById(String id) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataScource());
        String sql = "select * from product where pid = ?";
        Product product = null;
        try {
            product =(Product) runner.query(sql,new BeanHandler(Product.class),id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }

    @Override
    public List findByKeyWord(String kewword){
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataScource());
        kewword = "%"+kewword+"%";
        String sql = "select * from product where pname like ?";
        List list = null;
        try {
            list = (List) runner.query(sql,new BeanListHandler(Product.class),kewword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
